<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-17
 * Time: 下午5:31
 */

namespace Institution\Model;
use User\Api\UserApi;
use Think\Model;

class UserModel extends Model {

    protected $_validate = array(
        array('name', '1,15', -16, self::EXISTS_VALIDATE, 'length'),  //姓名2-6
        array('username', '', -3, self::EXISTS_VALIDATE, 'unique'), //用户名被占用
        array('username', '1,16', -1, self::EXISTS_VALIDATE, 'length'), //姓名长度不合法
        array('city', 'require', -15), //城市不能为空
        /* 验证邮箱 */
        array('email', 'email', -5, self::EXISTS_VALIDATE), //邮箱格式不正确
        array('email', '1,32', -6, self::EXISTS_VALIDATE, 'length'), //邮箱长度不合法
//        array('email', 'checkDenyEmail', -7, self::EXISTS_VALIDATE, 'callback'), //邮箱禁止注册
        array('email', '', -8, self::EXISTS_VALIDATE, 'unique'), //邮箱被占用

        /* 验证手机号码 */
        array('tel','/^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/',-9,self::EXISTS_VALIDATE),//手机号码不合法
        array('address', 'require', -13), //地址不能为空
    );

    //添加人员
    public function userAdd($data){
        if($this->create($data)){
            $uid = $this->add();
            return $uid?$uid:0;
        }else{
            return $this->getError();
        }
    }

    //修改人员信息
    public function userUpdate($data){
        $data = $this->create($data);
        if($data){
            $res = $this->data($data)->save();
            if($res){
                return  true;
            }else{
                return false;
            }
        }else{
            return $this->getError();
        }
    }
    /*
    * 用户登录
    */
    public function login($username,$password){
        $map['username'] = $username;
        //获取用户数据
        $user  = $this->where($map)->find();
        if(is_array($user) )
        {
            if($user['status']){
                if(md5($password) === $user['password']){
                    $allow = M('AuthGroupAccess')->where('uid='.$user['id'])->getField('group_id');
                    $where['description'] = array('LIKE','%普通用户%');
                    $arr   = M('AuthGroup')->where($where)->getField('id');
                    if($arr == $allow){
                        return -4;
                    }
                    return $user['id'];
                }else{
                    return -2;  //密码错误
                }
            }else{
                return -3; //用户禁用
            }
        }
        else
        {
            return -1;//用户不存在
        }
    }

    public function a_login($uid){
        /* 检测是否在当前应用注册 */
        $Model = M('User');
        $user = $Model->find($uid);
        if(!$user || 1 != $user['status']) {
            $this->error = '用户不存在或已被禁用！'; //应用级别禁用
            return false;
        }
        //记录行为
        action_log('user_login', 'member', $uid, $uid);
        /* 登录用户 */
        $this->autoLogin($user);
        return true;
    }

    private function autologin($user){
        $auth = array(
            'uid'=>$user['id'],
            'username'=>$user['username'],
			'role_id' => $user['typeid']
        );
        session('user_auth',$auth);
    }

    public function change_isIp($uid){
        $data['is_ip'] =1;
        $map['id'] = $uid;
        $this->where($map)->save($data);
        return true;
    }

    public function logout(){
        action_log(UID,'用户登录');
        session('user_auth', null);
    }

	/*
     * 用户自动登录
     */
    private function autoLogin_u($user,$remember=false){
        /*记录session和cookie*/
        $user['uid'] 		= $user['id'];
        $user['type_id'] 	= $user['type'];
        unset($user['password']);
        session('user_auth',$user);
        if($remember){
            $user1 = D('user_token')->where('uid='.$user['uid'])->find();
            $token = $user1['token'];
            if($user1 == null){
                $token = build_auth_key();
                $data['token'] = $token;
                $data['time'] = time();
                $data['uid'] = $user['uid'];
                D('user_token')->add($data);
            }
            if(!$this->getCookieUid()&& $remember){
                $expire = 3600 * 24 *7;
                cookie('OX_LOGGED_USER',$this->jiami($this->change().".{$user['uid']}.{$token}"), $expire);
            }
        }
    }
    public function a_login_u($uid){
        /* 检测是否在当前应用注册 */
        $Model = M('User');
        $user = $Model->find($uid);
        if(!$user || 1 != $user['status']) {
            $this->error = '用户不存在或已被禁用！'; //应用级别禁用
            return false;
        }
        //记录行为
        action_log('user_login', 'member', $uid, $uid);
        /* 登录用户 */
        $this->autoLogin_u($user);
        return true;
    }
	
	
	public function getCookieUid()
    {

        static $cookie_uid = null;
        if (isset($cookie_uid) && $cookie_uid !== null) {
            return $cookie_uid;
        }
        $cookie = cookie('OX_LOGGED_USER');
        $cookie = explode(".", $this->jiemi($cookie));
        $map['uid'] = $cookie[1];
        $user = D('user_token')->where($map)->find();
        $cookie_uid = ($cookie[0] != $this->change()) || ($cookie[2] != $user['token']) ? false : $cookie[1];
        $cookie_uid = $user['time'] - time() >= 3600 * 24 * 7 ? false : $cookie_uid;
        return $cookie_uid;
    }
	
	/**
     * 加密函数
     * @param string $txt 需加密的字符串
     * @param string $key 加密密钥，默认读取SECURE_CODE配置
     * @return string 加密后的字符串
     */
    private function jiami($txt, $key = null)
    {
        empty($key) && $key = $this->change();

        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_";
        $nh = rand(0, 64);
        $ch = $chars[$nh];
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = base64_encode($txt);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh + strpos($chars, $txt [$i]) + ord($mdKey[$k++])) % 64;
            $tmp .= $chars[$j];
        }
        return $ch . $tmp;
    }

    /**
     * 解密函数
     * @param string $txt 待解密的字符串
     * @param string $key 解密密钥，默认读取SECURE_CODE配置
     * @return string 解密后的字符串
     */
    private function jiemi($txt, $key = null)
    {
        empty($key) && $key = $this->change();

        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-=_";
        $ch = $txt[0];
        $nh = strpos($chars, $ch);
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = substr($txt, 1);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = strpos($chars, $txt[$i]) - $nh - ord($mdKey[$k++]);
            while ($j < 0) {
                $j += 64;
            }
            $tmp .= $chars[$j];
        }

        return base64_decode($tmp);
    }

    private function change()
    {
        preg_match_all('/\w/', C('DATA_AUTH_KEY'), $sss);
        $str1 = '';
        foreach ($sss[0] as $v) {
            $str1 .= $v;
        }
        return $str1;
    }
	
}